<template>
	<view class="container" :style="{height: screenHeight + 'px'}">
		<!-- 顶部标题和时间状态 -->
		<view class="header">
			<text class="title">学生签到系统</text>
			<view class="time-status" :class="currentTimeStatus">
				<text class="status-text">{{ timeStatusText }}</text>
				<text class="time-range">{{ timeRangeText }}</text>
				<text class="time-remaining" v-if="isSignInTime && timeRemaining > 0">
					剩余时间: {{ formatTime(timeRemaining) }}
				</text>
				<text class="time-ended" v-else-if="!isSignInTime">
					当前不在签到时间内
				</text>
			</view>
		</view>

		<!-- 顶部统计区域 -->
		<view class="stats-container" :class="{'stats-container-animate': statsAnimate}">
			<view class="stat-item" @click="toggleFilter('all')" :class="{active: currentFilter === 'all'}">
				<text class="stat-number">{{ totalStudents }}</text>
				<text class="stat-label">总人数</text>
			</view>
			<view class="stat-item" @click="toggleFilter('present')" :class="{active: currentFilter === 'present'}">
				<text class="stat-number present">{{ presentCount + lateCount }}</text>
				<text class="stat-label">{{ isCheckOutTime ? '已签退' : '已签到' }}</text>
			</view>
			<view class="stat-item" @click="toggleFilter('absent')" :class="{active: currentFilter === 'absent'}">
				<text class="stat-number absent">{{ absentCount }}</text>
				<text class="stat-label">{{ isCheckOutTime ? '未签退' : '未签到' }}</text>
			</view>
			<view class="stat-item" @click="toggleFilter('late')" :class="{active: currentFilter === 'late'}">
				<text class="stat-number late">{{ lateCount }}</text>
				<text class="stat-label">迟到</text>
			</view>
		</view>

		<!-- 学生卡片列表 -->
		<scroll-view class="student-list" scroll-y>
			<view class="student-grid">
				<view v-for="(student, index) in filteredStudents" :key="student.id" class="student-card" :class="{
            'selected': selectedStudents.includes(student.id),
            'present': student.status === 'present',
            'absent': student.status === 'absent',
            'late': student.status === 'late'
          }" @click="toggleSelect(student.id)" @touchstart="startScale(index)" @touchend="endScale(index)"
					:style="{transform: cardScales[index]}">
					<image class="avatar" :src="student.avatar || '/static/aver1.jpg'"></image>
					<text class="name">{{ student.name }}</text>
					<view class="status-badge" :class="student.status">
						<text>{{ getStatusText(student.status) }}</text>
					</view>
					<view class="status-icon">
						<text v-if="student.status === 'present'" class="iconfont icon-check">✓</text>
						<text v-if="student.status === 'absent'" class="iconfont icon-close">✗</text>
						<text v-if="student.status === 'late'" class="iconfont icon-late">⌚</text>
					</view>
					<text class="check-in-time" v-if="student.status !== ''">{{ student.checkInTime }}</text>
				</view>
			</view>
		</scroll-view>

		<!-- 固定在底部的操作按钮 -->
		<view class="action-buttons-fixed">
			<view class="action-buttons">
				<button class="btn present-btn" @click="markPresent"
					:class="{'pulse': selectedStudents.length > 0, 'disabled': !isSignInTime}"
					:disabled="!isSignInTime">
					<text class="btn-icon">✓</text>
					<text>{{ isCheckOutTime ? '签退' : '签到' }}</text>
				</button>
				<button class="btn absent-btn" @click="showAbsentReasonDialog"
					:class="{'pulse': selectedStudents.length > 0}">
					<text class="btn-icon">✗</text>
					<text>{{ isCheckOutTime ? '未签退' : '未到' }}</text>
				</button>
			</view>
		</view>

		<!-- 未到校原因弹窗 -->
		<uni-popup ref="absentPopup" type="dialog">
			<uni-popup-dialog mode="input" :title="'未到原因 - ' + timeStatusText" placeholder="请输入未到原因"
				@confirm="markAbsent"></uni-popup-dialog>
		</uni-popup>

		<!-- 签到成功提示 -->
		<view class="toast-message" v-if="showToast" :class="toastClass">
			<text>{{ toastMessage }}</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				screenHeight: uni.getSystemInfoSync().windowHeight,
				students: [{
						id: 1,
						name: '张三',
						avatar: '',
						status: 'absent',
						checkInTime: ''
					},
					{
						id: 2,
						name: '李四',
						avatar: '',
						status: 'absent',
						checkInTime: ''
					},
					{
						id: 3,
						name: '王五',
						avatar: '',
						status: 'absent',
						checkInTime: ''
					},
					{
						id: 4,
						name: '赵六',
						avatar: '',
						status: 'absent',
						checkInTime: ''
					},
					{
						id: 5,
						name: '钱七',
						avatar: '',
						status: 'absent',
						checkInTime: ''
					},
					{
						id: 6,
						name: '孙八',
						avatar: '',
						status: 'absent',
						checkInTime: ''
					},
					{
						id: 7,
						name: '周九',
						avatar: '',
						status: 'absent',
						checkInTime: ''
					},
					{
						id: 8,
						name: '吴十',
						avatar: '',
						status: 'absent',
						checkInTime: ''
					},
				],
				selectedStudents: [],
				currentFilter: 'all',
				cardScales: [],
				showToast: false,
				toastMessage: '',
				toastClass: '',
				statsAnimate: false,
				currentTimeStatus: 'morning-in',
				timeStatusText: '上午签到',
				timeRangeText: '7:30-8:30',
				isSignInTime: false,
				isCheckOutTime: false, // 新增：是否为签退时间
				timeRemaining: 0,
				signInTimer: null,
				timeStatusMap: {
					'morning-in': {
						text: '上午签到',
						range: '7:30-8:30'
					},
					'morning-out': {
						text: '上午签退',
						range: '10:30-11:30'
					},
					'afternoon-in': {
						text: '下午签到',
						range: '14:30-15:30'
					},
					'afternoon-out': {
						text: '下午签退',
						range: '17:30-18:30'
					}
				},
				timeConfig: {
					'morning-in': {
						start: 450,
						end: 510
					}, // 7:30-8:30 (分钟数)
					'morning-out': {
						start: 630,
						end: 690
					}, // 10:30-11:30
					'afternoon-in': {
						start: 870,
						end: 930
					}, // 14:30-15:30
					'afternoon-out': {
						start: 1050,
						end: 1110
					} // 17:30-18:30
				},
				// 模拟时间检查，实际使用时应该用真实时间
				mockCurrentHour: new Date().getHours(),
				mockCurrentMinute: new Date().getMinutes()
			}
		},
		computed: {
			totalStudents() {
				return this.students.length
			},
			presentCount() {
				return this.students.filter(s => s.status === 'present').length
			},
			absentCount() {
				return this.students.filter(s => s.status === 'absent').length
			},
			lateCount() {
				return this.students.filter(s => s.status === 'late').length
			},
			filteredStudents() {
				if (this.currentFilter === 'all') return this.students
				if (this.currentFilter === 'present') {
					return this.students.filter(s => s.status === 'present' || s.status === 'late')
				}
				return this.students.filter(s => s.status === this.currentFilter)
			}
		},
		created() {
			// 初始化卡片缩放状态
			this.cardScales = this.students.map(() => 'scale(1)')

			// 启动统计区域动画
			setTimeout(() => {
				this.statsAnimate = true
			}, 300)

			// 根据时间设置状态
			this.setTimeStatus()
			this.checkSignInTime()

			// 模拟时间检查，实际使用时应该用定时器检查真实时间
			// setInterval(this.checkTimeStatus, 60000) // 每分钟检查一次
		},
		beforeDestroy() {
			this.stopCountdown()
		},
		methods: {
			setTimeStatus() {
			    const hour = this.mockCurrentHour
			    const minute = this.mockCurrentMinute
			    const totalMinutes = hour * 60 + minute
			
			    // 上午签到时间 7:30-8:30
			    if (totalMinutes >= 450 && totalMinutes < 510) {
			        this.currentTimeStatus = 'morning-in'
			        this.isCheckOutTime = false
			    }
			    // 上午其他时间
			    else if (totalMinutes >= 510 && totalMinutes < 630) {
			        this.currentTimeStatus = 'morning-in' // 显示上午签到状态但不在签到时间
			        this.isCheckOutTime = false
			    }
			    // 上午签退时间 10:30-11:30
			    else if (totalMinutes >= 630 && totalMinutes < 690) {
			        this.currentTimeStatus = 'morning-out'
			        this.isCheckOutTime = true
			    }
			    // 上午签退后到下午签到前
			    else if (totalMinutes >= 690 && totalMinutes < 870) {
			        this.currentTimeStatus = 'afternoon-in' // 显示下午签到状态但不在签到时间
			        this.isCheckOutTime = false
			    }
			    // 下午签到时间 14:30-15:30
			    else if (totalMinutes >= 870 && totalMinutes < 930) {
			        this.currentTimeStatus = 'afternoon-in'
			        this.isCheckOutTime = false
			    }
			    // 下午其他时间
			    else if (totalMinutes >= 930 && totalMinutes < 1050) {
			        this.currentTimeStatus = 'afternoon-in' // 显示下午签到状态但不在签到时间
			        this.isCheckOutTime = false
			    }
			    // 下午签退时间 17:30-18:30
			    else if (totalMinutes >= 1050 && totalMinutes < 1110) {
			        this.currentTimeStatus = 'afternoon-out'
			        this.isCheckOutTime = true
			    }
			    // 其他时间（晚上和凌晨）
			    else {
			        // 根据当前时间决定显示上午还是下午状态
			        if (hour < 12) {
			            this.currentTimeStatus = 'morning-in'
			        } else {
			            this.currentTimeStatus = 'afternoon-in'
			        }
			        this.isCheckOutTime = false
			    }
			
			    this.timeStatusText = this.timeStatusMap[this.currentTimeStatus].text
			    this.timeRangeText = this.timeStatusMap[this.currentTimeStatus].range
			},
			checkSignInTime() {
			    const hour = this.mockCurrentHour
			    const minute = this.mockCurrentMinute
			    const totalMinutes = hour * 60 + minute
			    const config = this.timeConfig[this.currentTimeStatus]
			
			    if (config) {
			        this.isSignInTime = totalMinutes >= config.start && totalMinutes <= config.end
			        this.timeRemaining = Math.max(0, config.end - totalMinutes) * 60
			
			        // 启动倒计时
			        if (this.isSignInTime) {
			            this.startCountdown()
			        } else {
			            this.stopCountdown()
			        }
			    } else {
			        this.isSignInTime = false
			        this.stopCountdown()
			    }
			},

			startCountdown() {
				this.stopCountdown()
				this.signInTimer = setInterval(() => {
					if (this.timeRemaining > 0) {
						this.timeRemaining--
					} else {
						this.isSignInTime = false
						this.stopCountdown()
					}
				}, 1000)
			},

			stopCountdown() {
				if (this.signInTimer) {
					clearInterval(this.signInTimer)
					this.signInTimer = null
				}
			},

			formatTime(seconds) {
				const mins = Math.floor(seconds / 60)
				const secs = seconds % 60
				return `${mins}:${secs < 10 ? '0' : ''}${secs}`
			},

			getStatusText(status) {
				const map = {
					'present': this.isCheckOutTime ? '已签退' : '已签到',
					'absent': this.isCheckOutTime ? '未签退' : '未签到',
					'late': '迟到',
					'': this.isCheckOutTime ? '未签退' : '未签到'
				}
				return map[status] || (this.isCheckOutTime ? '未签退' : '未签到')
			},

			toggleSelect(studentId) {
				const index = this.selectedStudents.indexOf(studentId)
				if (index === -1) {
					this.selectedStudents.push(studentId)
				} else {
					this.selectedStudents.splice(index, 1)
				}
			},

			toggleFilter(filter) {
				this.currentFilter = filter
				// 添加点击动画
				this.statsAnimate = false
				setTimeout(() => {
					this.statsAnimate = true
				}, 50)
			},

			startScale(index) {
				this.$set(this.cardScales, index, 'scale(0.95)')
			},

			endScale(index) {
				this.$set(this.cardScales, index, 'scale(1)')
			},

			markPresent() {
				if (!this.isSignInTime) {
					uni.showToast({
						title: '当前不在签到时间内',
						icon: 'none'
					})
					return
				}

				if (this.selectedStudents.length === 0) {
					uni.showToast({
						title: '请选择学生',
						icon: 'none'
					})
					return
				}

				const currentTime = this.mockCurrentHour * 60 + this.mockCurrentMinute
				let isLate = false
				const config = this.timeConfig[this.currentTimeStatus]

				// 检查是否迟到（上午签到8:00后，下午签到15:00后）
				if (this.currentTimeStatus === 'morning-in' && currentTime > 480) {
					isLate = true
				} else if (this.currentTimeStatus === 'afternoon-in' && currentTime > 900) {
					isLate = true
				}

				this.students = this.students.map(student => {
					if (this.selectedStudents.includes(student.id)) {
						return {
							...student,
							status: isLate ? 'late' : 'present',
							checkInTime: new Date().toLocaleTimeString()
						}
					}
					return student
				})

				const message = isLate ?
					`${this.selectedStudents.length}名学生标记为迟到` :
					`${this.selectedStudents.length}名学生${this.isCheckOutTime ? '签退' : '签到'}成功`

				this.showSuccessToast(message)
				this.selectedStudents = []
			},

			showAbsentReasonDialog() {
				if (this.selectedStudents.length === 0) {
					uni.showToast({
						title: '请选择学生',
						icon: 'none'
					})
					return
				}

				this.$refs.absentPopup.open()
			},

			markAbsent(reason) {
				this.students = this.students.map(student => {
					if (this.selectedStudents.includes(student.id)) {
						return {
							...student,
							status: 'absent',
							absentReason: reason,
							checkInTime: new Date().toLocaleTimeString()
						}
					}
					return student
				})

				this.showWarningToast(`${this.selectedStudents.length}名学生标记为${this.isCheckOutTime ? '未签退' : '未到'}`)
				this.selectedStudents = []
			},

			showSuccessToast(message) {
				this.toastMessage = message
				this.toastClass = 'toast-success'
				this.showToast = true

				setTimeout(() => {
					this.showToast = false
				}, 2000)
			},

			showWarningToast(message) {
				this.toastMessage = message
				this.toastClass = 'toast-warning'
				this.showToast = true

				setTimeout(() => {
					this.showToast = false
				}, 2000)
			}
		}
	}
</script>



<style lang="scss" scoped>
	$primary-color: #5a8dee;
	$success-color: #67c23a;
	$warning-color: #e6a23c;
	$danger-color: #f56c6c;
	$late-color: #ff9800;
	$disabled-color: #c8c9cc;
	$bg-color: #f5f7fa;
	$info-color: #ff9800;
	$card-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
	$fixed-btn-height: 80px;

	.container {
		display: flex;
		flex-direction: column;
		background-color: $bg-color;
		padding: 20px 20px $fixed-btn-height + 20px;
		position: relative;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15px;

		.title {
			font-size: 24px;
			font-weight: bold;
			color: $primary-color;
			text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		}

		.time-status {
			padding: 8px 15px;
			border-radius: 20px;
			background: linear-gradient(135deg, $primary-color, #7ba1f0);
			color: white;
			display: flex;
			flex-direction: column;
			align-items: center;
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

			&.morning-in {
				background: linear-gradient(135deg, $success-color, #85ce61);
			}

			&.morning-out {
				background: linear-gradient(135deg, $warning-color, #ebb563);
			}

			&.afternoon-in {
				background: linear-gradient(135deg, $primary-color, #7ba1f0);
			}

			&.afternoon-out {
				background: linear-gradient(135deg, $warning-color, #ebb563);
			}

			.status-text {
				font-size: 16px;
				font-weight: 500;
			}

			.time-range {
				font-size: 12px;
				opacity: 0.9;
			}

			.time-remaining {
				font-size: 12px;
				color: #fff;
				margin-top: 3px;
			}

			.time-ended {
				font-size: 12px;
				color: #ffeb3b;
				margin-top: 3px;
			}
		}
	}

	.stats-container {
		display: flex;
		justify-content: space-around;
		margin-bottom: 20px;
		padding: 15px;
		background: white;
		border-radius: 12px;
		box-shadow: $card-shadow;
		transition: all 0.3s ease;

		&-animate {
			transform: translateY(0);
			opacity: 1;
		}

		&:not(&-animate) {
			transform: translateY(-20px);
			opacity: 0;
		}
	}

	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 10px 15px;
		border-radius: 8px;
		transition: all 0.3s ease;

		&.active {
			background-color: rgba($primary-color, 0.1);

			.stat-number {
				color: $primary-color;
				font-weight: bold;
			}
		}
	}

	.stat-number {
		font-size: 24px;
		font-weight: 500;
		margin-bottom: 5px;

		&.present {
			color: $success-color;
		}

		&.absent {
			color: $danger-color;
		}

		&.late {
			color: $late-color;
		}
	}

	.stat-label {
		font-size: 14px;
		color: $info-color;
	}

	.student-list {
		flex: 1;
		margin-bottom: 15px;
	}

	.student-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
		gap: 15px;
	}

	.student-card {
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 15px;
		background: white;
		border-radius: 12px;
		box-shadow: $card-shadow;
		transition: all 0.3s ease;
		overflow: hidden;

		&.selected {
			background-color: rgba($primary-color, 0.1);
			box-shadow: 0 4px 16px rgba($primary-color, 0.2);
		}

		&.present {
			border: 2px solid $success-color;

			.status-icon {
				background-color: $success-color;
			}
		}

		&.absent {
			border: 2px solid $danger-color;

			.status-icon {
				background-color: $danger-color;
			}
		}

		&.late {
			border: 2px solid $late-color;

			.status-icon {
				background-color: $late-color;
			}
		}
	}

	.avatar {
		width: 80px;
		height: 80px;
		border-radius: 50%;
		margin-bottom: 10px;
		object-fit: cover;
		border: 3px solid #eee;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	.name {
		font-size: 16px;
		font-weight: 500;
		margin-bottom: 5px;
		text-align: center;
	}

	.status-badge {
		padding: 3px 10px;
		border-radius: 10px;
		font-size: 12px;
		margin-bottom: 8px;
		color: white;

		&.present {
			background-color: $success-color;
		}

		&.absent {
			background-color: $danger-color;
		}

		&.late {
			background-color: $late-color;
		}
	}

	.time-status-badge {
		padding: 2px 8px;
		border-radius: 8px;
		font-size: 10px;
		color: white;
		margin-bottom: 5px;

		&.morning-in {
			background-color: rgba($success-color, 0.7);
		}

		&.morning-out {
			background-color: rgba($warning-color, 0.7);
		}

		&.afternoon-in {
			background-color: rgba($primary-color, 0.7);
		}

		&.afternoon-out {
			background-color: rgba($warning-color, 0.7);
		}
	}

	.check-in-time {
		font-size: 10px;
		color: #999;
		margin-top: 5px;
	}

	.status-icon {
		position: absolute;
		top: 0px;
		right: 0px;
		width: 24px;
		height: 24px;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
		font-size: 14px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
	}

	/* 固定在底部的操作按钮 */
	.action-buttons-fixed {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: white;
		padding: 10px 20px;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
		z-index: 100;
	}

	.action-buttons {
		display: flex;
		justify-content: space-between;

		.btn {
			flex: 1;
			margin: 0 10px;
			height: 50px;
			border-radius: 25px;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 16px;
			font-weight: 500;
			transition: all 0.3s ease;

			.btn-icon {
				margin-right: 8px;
				font-weight: bold;
			}

			&.pulse {
				animation: pulse 1.5s infinite;
			}

			&.disabled {
				opacity: 0.6;
				background: $disabled-color !important;
			}
		}

		.present-btn {
			background: linear-gradient(135deg, $success-color, #85ce61);
			color: white;
		}

		.absent-btn {
			background: linear-gradient(135deg, $danger-color, #f78989);
			color: white;
		}
	}

	.uni-popup-dialog {
		border-radius: 12px !important;
	}

	.toast-message {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		padding: 15px 25px;
		border-radius: 25px;
		color: white;
		font-size: 16px;
		font-weight: 500;
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
		z-index: 999;
		animation: fadeIn 0.3s, fadeOut 0.3s 1.7s;

		&.toast-success {
			background: rgba($success-color, 0.9);
		}

		&.toast-warning {
			background: rgba($warning-color, 0.9);
		}
	}

	@keyframes pulse {
		0% {
			transform: scale(1);
			box-shadow: 0 0 0 0 rgba(90, 141, 238, 0.7);
		}

		70% {
			transform: scale(1.02);
			box-shadow: 0 0 0 10px rgba(90, 141, 238, 0);
		}

		100% {
			transform: scale(1);
			box-shadow: 0 0 0 0 rgba(90, 141, 238, 0);
		}
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translate(-50%, -40%);
		}

		to {
			opacity: 1;
			transform: translate(-50%, -50%);
		}
	}

	@keyframes fadeOut {
		from {
			opacity: 1;
			transform: translate(-50%, -50%);
		}

		to {
			opacity: 0;
			transform: translate(-50%, -60%);
		}
	}

	/* 响应式调整 */
	@media (max-width: 768px) {
		.student-grid {
			grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
		}

		.action-buttons .btn {
			font-size: 14px;
			padding: 0 5px;
		}
	}
</style>